import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.StringTokenizer;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;

public class CopyOfReservationClient extends JFrame implements ActionListener {

	/**
	 * 
	 */
	private static final long serialVersionUID = 3055444881389336738L;
	public static final String SERVER_URL = "http://local.server/";
	public static final String TABLES_LIST_ACTION = "tables";
	public static final String TABLES_RESET_ACTION = "reset";
	public static final String TABLE_RESERVE_ACTION = "reserve";
	public static final String TABLE_CHECK_ACTION = "check";
	public static final String POSITIVE_ANSWER = "true";
	public static final String NEGATIVE_ANSWER = "false";
	
	public CopyOfReservationClient() {
		super("ReservationClient");
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		setSize(600, 400);
		GridLayout layout = new GridLayout(0,3);
		getContentPane().setLayout(layout);
		showTables();
		setVisible(true);
	}

	public void showTables() {
		// Construct data
		try {
			// Send data
			URL url = new URL(SERVER_URL + TABLES_LIST_ACTION + ".php");
			
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			Document doc = db.parse(url.openStream());
			
			NodeList nl = doc.getFirstChild().getChildNodes();
			for(int i=0, n=nl.getLength(); i < n; i++) {
				Node item = nl.item(i);
				if(!item.getNodeName().equals("#text")) {
					String tableId = item.getAttributes().getNamedItem("id").getTextContent();
					JButton reserveButton = new JButton();
					reserveButton.setText("Rezervuoti " + tableId + " stalelį");
					reserveButton.setActionCommand(TABLE_RESERVE_ACTION + " " + tableId);
					reserveButton.addActionListener(this);
					reserveButton.setName(TABLE_RESERVE_ACTION);
					if(!checkTable(tableId)) {
						reserveButton.setEnabled(false);
					}
					getContentPane().add(reserveButton);
				}
			}
			
			JButton reserveButton = new JButton();
			reserveButton.setText(TABLE_RESERVE_ACTION);
			reserveButton.setActionCommand(TABLE_RESERVE_ACTION + " 2");
			reserveButton.addActionListener(this);
			reserveButton.setName(TABLE_RESERVE_ACTION);
			getContentPane().add(reserveButton);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		new CopyOfReservationClient();
	}
	
	public boolean checkTable(String tableId) {
		try {
			String args = URLEncoder.encode("table", "UTF-8") + "="
					+ URLEncoder.encode(tableId, "UTF-8");
						
			URL url = new URL(SERVER_URL + TABLE_CHECK_ACTION + ".php?" + args);
			
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			Document doc = db.parse(url.openStream());
			
			String answer = doc.getFirstChild().getTextContent();
			
			System.out.println(SERVER_URL + TABLE_CHECK_ACTION + ".php?" + args + " " + tableId + " " + answer);
			
			return answer.equals(POSITIVE_ANSWER);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return false;
	}
	
	public void reserveTable(String tableId) {
		try {
			String args = URLEncoder.encode("table", "UTF-8") + "="
					+ URLEncoder.encode(tableId, "UTF-8");
						
			URL url = new URL(SERVER_URL + TABLE_RESERVE_ACTION + ".php?" + args);
			url.openStream();
			
			System.out.println(SERVER_URL + TABLE_RESERVE_ACTION + ".php?" + args);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void actionPerformed(ActionEvent event) {
		StringTokenizer st = new StringTokenizer(event.getActionCommand(), " ");
		if(st.countTokens() < 2) {
			return;
		}
		
		String action = st.nextToken();
		String tableId = st.nextToken();
		
		if( action.equals(TABLE_RESERVE_ACTION) ) {
			if(checkTable(tableId)) {
				reserveTable(tableId);
				
				if( event.getSource() instanceof JButton ) {
					((JButton) event.getSource()).setEnabled(false);
				}
			}
		}
	}
}
